package cn.ibizlab.core.authentication.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.HashMap;
import java.util.Map;
import static cn.ibizlab.core.authentication.constants.AuthenticationConstant.*;

/*
* 全局ldap配置
*   spring:
      # LDAP连接配置
      ldap:
        urls: ldaps://x.x.x.x:636/
        base: ou=xxx,dc=ad,dc=xxx,dc=com
        username: 用户
        password: 密码
*/
@Data
@Component
public class GlobalLdapConfig {

    @Value("${spring.ldap.urls:}")
    private String urls;
    @Value("${spring.ldap.base:}")
    private String base;
    @Value("${spring.ldap.username:}")
    private String username;
    @Value("${spring.ldap.password:}")
    private String password;
    @Value("${spring.ldap.uid:cn}")
    private String uid;
    @Value("${spring.ldap.ouBase:ou=users}")
    private String ouBase;
    @Value("${spring.ldap.objectClass:inetOrgPerson}")
    private String objectClass;
    private Map<String, String> defaultConfigMap;
    private String defaultConfigText;

    /**
     * 获取ldap配置参数map
     */
    public Map<String, String> getDefaultConfigMap()
    {
        if(defaultConfigMap != null)
            return defaultConfigMap;

        defaultConfigMap = new HashMap<>();
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_BASE, base);
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_USERNAME, username);
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_PASSWORD, password);
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_UID, uid);
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_OU_BASE,ouBase);
        defaultConfigMap.put(PROVIDER_LDAP_PARAM_OBJECT_CLASS, objectClass);

        return defaultConfigMap;
    }

    /**
     * 是否开启ldap配置
     * @return
     */
    public boolean enable(){
        return !ObjectUtils.isEmpty(urls);
    }

    /**
     * 获取ldap配置参数内容
     * @return
     */
    public String getDefaultConfigText(){

        if(!ObjectUtils.isEmpty(defaultConfigText))
            return defaultConfigText;

        String format = "%1$s=%2$s%3$s";
        StringBuilder config = new StringBuilder();
        config.append(String.format(format,PROVIDER_LDAP_PARAM_BASE,base,System.lineSeparator()));
        config.append(String.format(format,PROVIDER_LDAP_PARAM_USERNAME,username,System.lineSeparator()));
        config.append(String.format(format,PROVIDER_LDAP_PARAM_PASSWORD,password,System.lineSeparator()));
        config.append(String.format(format,PROVIDER_LDAP_PARAM_UID, uid,System.lineSeparator()));
        config.append(String.format(format,PROVIDER_LDAP_PARAM_OU_BASE, ouBase,System.lineSeparator()));
        config.append(String.format(format,PROVIDER_LDAP_PARAM_OBJECT_CLASS, objectClass,System.lineSeparator()));
        defaultConfigText = config.toString();

        return defaultConfigText;
    }

}
